<template>
  <!--供应商商品编辑-->
  <div class="app-container">
    <div class="container">
      <!--工具栏-->
      <div>
        <!--标签栏-->
        <el-tabs v-model="activeName" @tab-click="tabClick">
          <el-tab-pane label="全部宝贝" name="1"/>
          <el-tab-pane label="出售中的宝贝" name="2"/>
          <el-tab-pane label="仓库中的宝贝" name="3"/>
        </el-tabs>
        <el-form ref="query" :inline="true" :model="query" size="small" class="demo-form-inline" label-position="right">
          <el-form-item label="分类:" prop="second_variety_id">
            <el-cascader
              v-model="query.variety_id"
              :options="varietyList"
              :props="{ checkStrictly: true }"
              clearable/>
          </el-form-item>
          <el-form-item label="宝贝名称:" prop="name">
            <el-input
              v-model="query.name"
              clearable
              placeholder=""
              style="width:180px;"
              class="filter-item"
              @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="销量:" prop="sale">
            <el-select v-model="query.sale" clearable placeholder="销量" class="filter-item" style="width: 180px">
              <el-option v-for="item in saleOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间:" prop="time">
            <el-date-picker
              v-model="query.time"
              :picker-options="pickerOptions2"
              value-format="yyyy-MM-dd HH:mm"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              style="width:360px"/>
          </el-form-item>
          <el-form-item label="价格:" prop="price">
            <el-select v-model="query.price" clearable placeholder="价格" class="filter-item" style="width: 180px">
              <el-option v-for="item in priceOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="宝贝状态:" prop="state">
            <el-select v-model="query.state" clearable placeholder="宝贝状态" class="filter-item" style="width: 180px">
              <el-option v-for="item in stateOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
            <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--修改库存弹框-->
      <updateInventory ref="updateInventory"/>
      <!--事件按钮-->
      <div class="operate-container">
        <!-- 导出（查询）-->
        <el-button
          :loading="downloadLoading"
          plain
          size="mini"
          icon="el-icon-download"
          @click="download('0')">导出（查询）
        </el-button>
        <!-- 导出（勾选） -->
        <el-button
          :loading="downloadLoading"
          :disabled="$refs.table && $refs.table.selection.length === 0"
          plain
          size="mini"
          icon="el-icon-download"
          @click="download('1')"> 导出（勾选）
        </el-button>
      </div>
      <!--表格渲染-->
      <el-table v-loading="loading" ref="table" :data="data" size="small" style="width: 100%;">
        <el-table-column type="selection"/>
        <el-table-column v-if="show" label="商品id" prop="commodity_id" align="center"/>
        <el-table-column label="宝贝" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <img
              :src="scope.row.link_url ? scope.row.link_url[0].url : ''"
              alt="点击打开"
              class="el-avatar"
              @click="viewImg(scope.row.link_url ? scope.row.link_url[0].url : '')">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="variety_name" align="center"/>
        <el-table-column label="会员价" prop="vip_price" align="center"/>
        <el-table-column label="供应商名称" width="120" prop="supplier_name" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.supplier_name === '' || !scope.row.supplier_name"> -</div>
            <div v-else>{{ scope.row.supplier_name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="销量" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.deal_times + scope.row.app_times }}</div>
          </template>
        </el-table-column>
        <el-table-column label="库存" prop="inventory" align="center"/>
        <el-table-column label="置顶" prop="is_top" width="45" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.is_top === 0">否</div>
            <div v-if="scope.row.is_top === 1">是</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state" width="60" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.state === 0">已上架</div>
            <div v-if="scope.row.state === 1">仓库中</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="130" prop="create_date" align="center"/>
        <el-table-column label="操作" align="center" width="270">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="inventoryClick(scope.row.commodity_id)">修改库存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        background
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"/>
    </div>
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import {
  getCascadeVarietyList,
  downloadCommoditys
} from '@/api/mall/commodity'
import { downloadFile } from '@/utils/index'
import updateInventory from './updateInventory'
import timer from '@/api/mall/timer' // 时间对象
import { mapGetters } from 'vuex'

export default {
  components: { updateInventory },
  mixins: [initData],
  data() {
    return {
      pickerOptions2: timer.timer,
      activeName: '1',
      tabId: 1,
      show: false,
      varietyList: [],
      downloadLoading: false,
      delLoading: false,
      query: {
        variety_id: '',
        name: '',
        state: '',
        starttime: '',
        endtime: '',
        price: '',
        sale: '',
        supplier_name: '',
        time: ''
      },
      stateOptions: [
        { key: '', display_name: '全部' },
        { key: '0', display_name: '已上架' },
        { key: '1', display_name: '仓库中' }
      ],
      priceOptions: [
        { key: 'ASC', display_name: '由低到高' },
        { key: 'DESC', display_name: '由高到低' }
      ],
      saleOptions: [
        { key: 'ASC', display_name: '由低到高' },
        { key: 'DESC', display_name: '由高到低' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    // 获取商品分类
    getCascadeVarietyList().then(res => {
      this.varietyList = res.content
    })
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    beforeInit() {
      this.url = 'api/commodity-list'
      const sort = 'create_date,desc'
      // 思路：通过公司id+phone找用户信息，然后通过用户找到用户的部门信息，这里的供应商只是一个部门的概念，即供应商部门
      // 那么获取商品列表还是原来的那个接口，但是由于商品列表若在加上供应商的概念，那么就太混乱了，所以单独开了一个供应商页面
      // 这样做的好处是：页面定制化更加的干净，商品列表就是商品列表，属于公司，此页面属于定制化的业务，满足公司内部供应商部门
      // 注：此供应商是部门的概念，和产业路由器的供应商公司不是一个。系统存在两个供应商：供应商部门(满足巢尚甄选)，供应商公司（S2B2C）
      this.params = { page: this.page, size: this.size, sort: sort, tabId: this.tabId, phone: this.user.phone }
      // 查询条件组装为实体
      this.querySetObject()
      return true
    },
    querySetObject() {
      const query = this.query
      const name = query.name
      const variety_id = query.variety_id
      const state = query.state
      const supplier_name = query.supplier_name
      const price = query.price
      const sale = query.sale
      const time = query.time
      if (time !== '' && time !== undefined) {
        this.params['time'] = time.join('~')
      }
      if (name && name !== '' && time !== null) {
        this.params['name'] = name
      }
      if (variety_id && variety_id !== '' && variety_id !== null) {
        this.params['variety_id'] = variety_id.join(',')
      }
      if (state && state !== '' && state !== null) {
        this.params['state'] = state
      }
      if (supplier_name) {
        this.params['supplier_name'] = supplier_name
      }
      if (price && price !== '' && price !== null) {
        this.params['price'] = price
      }
      if (sale && sale !== '' && sale !== null) {
        this.params['sale'] = sale
      }
    },
    // 切换tab
    tabClick(tab, event) {
      this.tabId = tab.name
      this.page = 0
      this.$nextTick(() => {
        this.init()
      })
    },
    // 导出
    download(type) {
      // 从新获取查询条件
      this.querySetObject()
      this.downloadLoading = true
      let data = {}
      if (type === '0') {
        // 导出查询
        data = this.params
      } else {
        // 导出勾选
        const dataSelect = this.$refs.table.selection
        const commodity_ids = []
        for (let i = 0; i < dataSelect.length; i++) {
          commodity_ids.push(dataSelect[i].commodity_id)
        }
        data = { 'commodity_ids': commodity_ids }
      }
      downloadCommoditys(data).then(result => {
        downloadFile(result, '商品列表', 'xlsx')
        this.downloadLoading = false
      }).catch((err) => {
        console.log(err.response.data.message)
        this.downloadLoading = false
      })
    },
    // 修改库存
    inventoryClick(commodity_id) {
      this.$refs.updateInventory.dialog = true
      this.$refs.updateInventory.form.commodity_id = commodity_id
    },
    // 重置查询条件
    resetQuery() {
      this.$refs['query'].resetFields()
      this.query = {
        time: ''
      }
      this.queryOrderDate = ['', '']
      this.init()
    }
  }
}
</script>

<style scoped>

</style>
